package com.asset.salesforce.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.model.Call;
import com.asset.salesforce.model.CallData;
import com.asset.salesforce.model.CallDetails;
import com.asset.salesforce.model.CallDetailsList;
import com.asset.salesforce.model.CallList;
import com.asset.salesforce.model.Company;
import com.asset.salesforce.model.Contact;
import com.asset.salesforce.model.Employee;
import com.asset.salesforce.model.Lead;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CallService;
import com.asset.salesforce.service.CompanyService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.LeadService;

@Controller
public class CallController {

	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private ContactService contactService;
	
	@Autowired
	private CallService callService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private CalendarService calendarService;
	
	@Autowired
	private LeadService leadService;

	@RequestMapping(value="/getAllCalls/{id}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public CallList getAllCalls(@PathVariable String id){
		CallList callList = new CallList();	
		List<CallData>callData = new ArrayList<CallData>();
		List<Call> calls =callService.getCallByParentId(Integer.parseInt(id), "lead");
		for (Call call : calls) {
			CallData data = new CallData();
			data.setId(call.getId());
			if(call.getCrmStaff()!=null){
				Employee employee = employeeService.getById(call.getCrmStaff().getId());
				data.setCrmStaffName(employee.getfName());
			}
			if(call.getContactedPerson()!=null){
				Contact contact = contactService.getContactById(call.getContactedPerson().getId());
				data.setContactedPersonName(contact.getfName());
			}
			data.setDate(call.getDate());
			data.setStartTime(call.getStartTime());
			data.setEndTime(call.getEndTime());
			callData.add(data);
		}
		callList.setCallData(callData);
		return callList;
	}
	
	@RequestMapping(value="/getAllCallsByEmpId/{empId}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public CallList getAllCallsByEmpId(@PathVariable String empId){
		Employee employee = employeeService.getById(Integer.parseInt(empId));
		List<Lead>leads = leadService.getLeads(employee.getId());
		CallList appointmentList = new CallList();
		List<CallData>appointmentData = new ArrayList<CallData>();
		for (Lead lead : leads) {
			List<Call> appointments = callService.getCallByParentId(lead.getId(), "lead");
			for (Call appointment : appointments) {
				CallData data = new CallData();
				data.setId(appointment.getId());
				if(appointment.getCrmStaff()!=null){
					Employee salesMan = employeeService.getById(appointment.getCrmStaff().getId());
					data.setCrmStaffName(salesMan.getfName());
				}
				if(appointment.getContactedPerson()!=null){
					Contact contact = contactService.getContactById(appointment.getContactedPerson().getId());
					data.setContactedPersonName(contact.getfName());
				}
				data.setDate(appointment.getDate());
				data.setStartTime(appointment.getStartTime());
				data.setEndTime(appointment.getEndTime());
				appointmentData.add(data);
			}
			appointmentList.setCallData(appointmentData);
		}		
		return appointmentList;
	}
	
	@RequestMapping(value="/getCall/id={id}/empId={empId}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public Call getCall(@PathVariable String id,@PathVariable String empId){
		Call call = callService.getCallnById(new Call(), Integer.parseInt(id));
		Employee owner = employeeService.getById(Integer.parseInt(empId));
		call.setOwnerName(owner.getfName()+" "+owner.getlName());
		if(call.getCrmStaff()!=null){
			Employee employee = employeeService.getById(call.getCrmStaff().getId());
			call.setCrmStaffName(employee.getfName());
		}
		if(call.getContactedPerson()!=null){
			Contact contact = contactService.getContactById(call.getContactedPerson().getId());
			call.setContactedPersonName(contact.getfName());
		}
		return call;
	}
	private boolean isCallTimeValid(List<Call>calls,Integer inputedStartTime,Integer inputedEndTime,Date inputedDate){
		boolean sucess=true;
		for (Call call : calls) {
			String[] startTimeSplit = call.getStartTime().split(":");
			Integer startTime = (Integer.parseInt(startTimeSplit[0])*60)+
										Integer.parseInt(startTimeSplit[1]);
			
			String[] endTimeSplit = call.getEndTime().split(":");
			Integer endTime = (Integer.parseInt(endTimeSplit[0])*60)+
										Integer.parseInt(endTimeSplit[1]);
			
			long oneDay = 24 * 60 * 60 * 1000;
			long d1 = call.getDate().getTime() / oneDay;
			long d2 = inputedDate.getTime() / oneDay;
			
			if(d1>d2||d1<d2){
				sucess=true;
			}
			
			if(d1==d2){
				if(inputedStartTime>=endTime && inputedEndTime>inputedStartTime||inputedEndTime<=startTime&&inputedStartTime<inputedEndTime){
					sucess=true;
				}
				else{
					sucess=false;
				}
			}
		}
		return sucess;
	}
	public boolean isValid(Call callForm) {
		boolean success = false; 
		String[] startTimeSplit = callForm.getStartTime().split(":");
		Integer startTime = (Integer.parseInt(startTimeSplit[0])*60)+
									Integer.parseInt(startTimeSplit[1]);
		
		String[] endTimeSplit = callForm.getEndTime().split(":");
		Integer endTime = (Integer.parseInt(endTimeSplit[0])*60)+
									Integer.parseInt(endTimeSplit[1]);
		List<Call>calls = callService.getCallByParentId(callForm.getParentId(), callForm.getParentType());
		boolean isCallTimeValid = isCallTimeValid(calls, startTime, endTime, callForm.getDate());
		if(isCallTimeValid==false){
			success = false; 
		}
		else{
			success = true; 
		}
		return success;
	}
	@RequestMapping(value="/addCallDetails/{empId}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public CallDetailsList addCall(@PathVariable String empId){
		Employee owner = employeeService.getById(Integer.parseInt(empId));
		Company company = companyService.getCompanyById(new Company(), owner.getCompany().getId());
		List<Employee>crmStaff = companyService.getActivatedEmployeesByCompanyName(company.getCompanyName());
		List<Contact>contactedPersons = contactService.getAllContactbyCompany(company.getCompanyName());
		List<CallDetails>callDetails = new ArrayList<CallDetails>();
		CallDetails callDetails2 =  new CallDetails();
			for (Contact contact : contactedPersons) {
				callDetails2.setContactedPersonId(contact.getId());
				callDetails2.setContactedPersonName(contact.getfName());
			}
			for (Employee employee : crmStaff) {
				callDetails2.setCrmStaffId(employee.getId());
				callDetails2.setCrmStaffName(employee.getfName());
			}
			
			callDetails.add(callDetails2);
			
			CallDetailsList callDetailsList = new CallDetailsList();
			callDetailsList	.setOwnerName(owner.getfName());
			callDetailsList.setCallDetails(callDetails);
		return callDetailsList;
	}
	
	@RequestMapping(value="/addCall",method=RequestMethod.POST,consumes="application/json;charset=UTF-8")
	@ResponseBody
	public Call addCall(@RequestBody Call call){
		boolean isCallValid = isValid(call);
		if(isCallValid==false){
			System.out.println("failure");
			return null;
		}
		else{
			System.out.println("sucess");
			if(call.getCrmStaffId()!=null){
				Employee crmStaff = employeeService.getById(call.getCrmStaffId());
				call.setCrmStaff(crmStaff);
			}
			if(call.getContactedPersonId()!=null){
				Contact contact = contactService.getContactById(call.getContactedPersonId());
				call.setContactedPerson(contact);
			}
			callService.addCall(call);
			calendarService.callEvent(call);
			
			return call;
		}
	}
	
}

